#!/usr/bin/python3
# coding:utf-8
import threading
import subprocess
import time
from queue import Queue
from gooey import Gooey, GooeyParser
import re

# 初始化变量，ipSucess为存储可以ping通的IP列表，Work_Thread为后台工作进程数，ipQueue为执行命令的队列
ipSuccess = []
ipFail = []
Work_Thread = 50
ipQueue = Queue()


# @Gooey(program_name='Batch Ping Tool', language='chinese', menu=[{
#     'name': 'File',
#     'items': [{
#         'type': 'AboutDialog',
#         'menuTitle': 'About',
#         'name': 'A Batch Ping Tool',
#         'description': '仅供测试，版权没有，侵权不纠',
#         'version': '0.0.2',
#         'developer': 'wjj'
#     }]
# }])
@Gooey(program_name='Batch Ping Tool', language='chinese')
def main():

    parser = GooeyParser(description="使用本工具可批量验证主机是否存活")
    parser.add_argument(
        "Filename", metavar="选择文件", widget="FileChooser")

    args = parser.parse_args()

    filename = args.Filename
    print(filename, flush=True)
    start_time = time.time()
    try:
        files = open(filename)
        comp = re.compile(
            r'^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}')
        for line in files.readlines():
            line = line.strip('\n')
            if comp.match(line):
                ipQueue.put(line)
            # ipQueue.put(line)

         # 初始化线程池，并多线程调用pingIP函数
        threads = []
        for i in range(Work_Thread):
            thread = threading.Thread(target=pingIp)
            thread.start()
            threads.append(thread)
        for thread in threads:
            thread.join()

        print("Batch Ping Tool V0.1: BY WJJ\nHost UP:")
        for i in ipSuccess:
            print("%s\tUP" % i)
        print("\nHost Down:")
        for i in ipFail:
            print("%s\tDown" % i)

        # 打印提示信息，包括在线主机数和脚本执行时间
        time_info = format(time.time() - start_time, '.2f')
        total_num = str(len(ipSuccess)+len(ipFail))
        up_num = str(len(ipSuccess))
        down_num = str(len(ipFail))

        run_info = "Total: "+total_num+"\nUP: "+up_num + \
            "\nDown: "+down_num+"\nTime: " + time_info+"s"
        print('\n' + run_info, flush=True)

        # 释放无用资源
        ipSuccess.clear()
        ipFail.clear()
    except:
        print("文件打开出错!")


def pingIp():
    while not ipQueue.empty():
        ip = ipQueue.get()
        # 如果为linux或macos，此处cmd应为'ping -c 2 -W 5',命令行参数不太一致
        cmd = 'ping -n 2 -w 5 %s' % ip
        # 如果为linux或macos，此处subprocess.call参数需在后面补充shell=True
        DETACHED_PROCESS = 0x00000008
        p = subprocess.call(cmd, stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE, creationflags=DETACHED_PROCESS)
        # print(ip, True if res == 0 else False)
        # 如果返回值为0，代表ping命令正确返回，此处仅简单判断状态，后续可读取通道信息，获取延时数据，针对延时时长渲染其他的颜色
        if p == 0:
            ipSuccess.append(ip)
        else:
            ipFail.append(ip)


            # 从这里开始执行
if __name__ == '__main__':
    main()
